package com.zd.certificate.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
public class MultipleDataSourceConfig {



    /**
     * 主数据源
     */
    public static final String PRIMARY_DS = "primaryDataSource";
    /**
     * 其他数据数据源
     */
    public static final String DYNAMIC_DS = "dynamicDataSource";

    /**
     * 初始化系统默认数据源
     * @return
     */
    @Bean(name=PRIMARY_DS)
    public DataSource primaryDataSource(@Qualifier("primaryProperties") PrimaryProperties primaryProperties){// @Qualifier 他是可以这样子注入的呀 动态的获取配置文件中的值
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(primaryProperties.getUrl());
        dataSource.setUsername(primaryProperties.getUsername());
        dataSource.setPassword(primaryProperties.getPassword());
        dataSource.setDriverClassName(primaryProperties.getDriverClassName());
        return dataSource;
    }

    /**
     * 初始化动态数据源管理器
     * 将默认数据源加入管理器
     * @return
     */
    @Primary
    @Bean(name = DYNAMIC_DS)
    @DependsOn(PRIMARY_DS)
    public DataSource dynamicDataSource(@Qualifier(PRIMARY_DS) DataSource dataSource){
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setDataSource(0,dataSource);
        return dynamicDataSource;
    }

    /**
     * 初始化事务管理器
     * 将动态数据源管理器加入
     * @return
     */
    @Bean
    @Primary
    @DependsOn(DYNAMIC_DS)
    public PlatformTransactionManager transactionManager(@Qualifier(DYNAMIC_DS) DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }


    @Bean
    @Primary
    @DependsOn(DYNAMIC_DS)
    public SqlSessionFactory sqlSessionFactory(@Qualifier(DYNAMIC_DS) DataSource dataSource)throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml")
        );
        return sessionFactory.getObject();
    }





}
